#!/usr/bin/env python
#-*- coding:utf-8 -*-

import os
import sys
import string
import json
import MySQLdb
import subprocess
from Tools import connectMySQL
import ConfigParser

#read config                                                                
cf = ConfigParser.ConfigParser()
#cf.read(os.path.dirname(os.path.realpath(__file__))+"../Tools/settings.conf")
cf.read("/opt/wanalytics/Tools/settings.conf")
host = cf.get("MySQL", "host")
user = cf.get("MySQL", "user")
passwd = cf.get("MySQL", "passwd")
dbMobileProduction = cf.get("MySQL", "dbMobileProduction")
dbGuid = cf.get("MySQL", "dbGuid")

program_path = "/opt/wanalytics"
kmysqlduplicateentry = 1062

def import_guid(filename):
    try:
        db = connectMySQL.connMySQL_guid()
    except MySQLdb.Error, e:
        print e
    cursor = db.cursor()

    try:
        cursor.execute("drop table if exists `tmp_import`")
        cursor.execute('''
            create table if not exists `tmp_import` (
                `guid` varchar(200) NOT NULL DEFAULT '',
                `pid` char(16) NOT NULL DEFAULT '',
                `os` varchar(64) NOT NULL DEFAULT '',
                `os_ver` varchar(64) NOT NULL DEFAULT '',
                `btype` varchar(64) NOT NULL DEFAULT '',
                `brand` varchar(64) NOT NULL DEFAULT '',
                `operator` varchar(64) NOT NULL DEFAULT '',
                `client_ver` varchar(64) NOT NULL DEFAULT '',
                `deviceid` varchar(64) NOT NULL DEFAULT '',
                `regtime` int(11) NOT NULL DEFAULT '0',
                `lasttime` int(11) NOT NULL DEFAULT '0',
                `guid_diff` char(32) NOT NULL DEFAULT ''
            )
        ''')
        p = subprocess.Popen("""echo \"load data infile '%s' into table tmp_import fields terminated by ','  optionally enclosed by '\\"' escaped by '\\"' lines terminated by '\\n'\" | mysql -u%s -p%s -h%s %s""" %(filename,user,passwd,host,dbGuid),shell=True)
        output_stream, error_stream = p.communicate()
#print output_stream
#        print error_stream
        cursor.execute("update tmp_import set guid = md5(guid)")
        cursor.execute("update tmp_import set guid = guid_diff where guid_diff != ''");
    except MySQLdb.Error, e:
        raise e

    cursor.execute("select * from tmp_import")
    rows = cursor.fetchall()

    for row in rows:
        try:
            sql = "INSERT INTO `clientUser`(guid,pid,os,os_ver,btype,brand,operator,client_ver,deviceid,regtime,lasttime) VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"
            param = (row[0],row[1],row[2],row[3],row[4],row[5],row[6],row[7],row[8],row[9],row[10])
            cursor.execute(sql, param) 
        except MySQLdb.IntegrityError, message:
            errorcode = message[0]
            if errorcode == kmysqlduplicateentry:
                pass
            else:
                raise message
    db.close()

if __name__ == '__main__':
    import_guid(sys.argv[1]);
